<?php
/**
 * 认证规则管理
 * User: hanbing
 * Date: 14-10-15
 * Time: 下午3:40
 */

namespace Admin\Controller;
use Common\Controller\AdminCommonController;
use Think\Auth;

class RulesController extends AdminCommonController {

    protected $separated = '&nbsp;&nbsp;&nbsp;&nbsp;';

    /*
    * 规则管理
    * */
    public function index(){
        if(S(C('DB_PREFIX').'_sys_rule_list_cache_html')){
            $html = S(C('DB_PREFIX').'_sys_rule_list_cache_html');
        }else{
            $this->auth = new Auth();
            $where = array();
            $where['id'] = array('gt',0);
            $rules = $this->auth->getRoleAuthListStructure($where);
            $html = $this->getHtml($rules);
            S(C('DB_PREFIX').'_sys_rule_list_cache_html',$html);
        }
        $this->assign('html',$html);
        $this->display();
    }

    /*
     * 递归输出html
     * */
    private function getHtml($list){
        $str = '<ul>';
        $url = C('TMPL_PARSE_STRING.__PUBLIC__');
        foreach($list as $value){
            $str .= '<li><p>';
            if($value['child']){
                $str .='<img src="'.$url.'/Admin/images/on.png" id="img_218">';
            }else{
                $str .='<img src="'.$url.'/Admin/images/off.png" id="img_218">';
            }

            $str .= '<span class="title">'.$value['title'].'</span><span class="fr">';
            /*$str .='<a href="/Rules/add?id='.$value["id"].'&g=sub">添加子规则</a> -';*/
            $str .='<a href="javascript:void(0);" class="add_rules" data-id="'.$value["id"].'" >添加子规则</a> -';
            /*$str .='<a href="/Rules/edit?id='.$value["id"].'">修改</a> - ';*/
            $str .='<a href="javascript:void(0);" class="edit_rules" data-id="'.$value['id'].'">修改</a> - ';
            $str .='<a class="del_sub_rules" data-id="'.$value["id"].'" style="cursor: pointer">删除</a></span></p>';
            if($value['child']){
                $str .= $this->getHtml($value['child']);
            }
            $str .= '</li>';
        }
        $str .= '</ul>';
        return $str;
    }

    /*
     * 添加规则
     * */
    public function add(){
        $this->auth = new Auth();
        $id = I('get.id');
        if(IS_POST){
            $name = I('post.name');
            $title = I('post.title');
            $pid = I('post.pid');
            $status = I('post.status',1);
            $sort = I('post.sort');
            if(empty($name)) $this->returnData('规则名称不能为空！');
            if(abslength($name) > 50){
                $this->returnData('规则名称不能超过50个字符！');
            }
            if(empty($title)) $this->$this->returnData('显示名称不能为空！');
            if(abslength($title) > 30){
                $this->returnData('显示名称不能超过30个字符！');
            }

            //判断规则是否存在
            if($this->getRulesField(array('name'=>$name,'pid'=>$pid),'id')){
                $this->returnData('该规则名称已存在！');
            }

            if(empty($pid)) $pid = 0;
            if(empty($sort)) $sort = 0;

            if($pid>0){
                $detail = $this->auth->getRulesInfo($pid);
                if(!$detail)$this->returnData('该规则不存在！');
                $data['path'] = $detail['path'];
            }else{
                $data['path'] = '';
            }
            $data['name'] = $name;
            $data['pid'] = $pid;
            $data['status'] = $status;
            $data['sort'] = $sort;
            $data['title'] = $title;
            $data['tid'] = empty($detail['tid'])?0:$detail['tid'];

            $result = $this->auth->addRules($data);
            if($result){
                unset($detail);
                unset($data);

                if($status == 1){
                    $html = $this->get_rules_html($result,$title);
                }
                $this->clearCache();
                $this->returnData('添加规则成功！',1,$html);
            }else{
                $this->returnData('添加规则失败！');
            }

        }else{
            $rules = $this->auth->getRoleAuthListStructure(array('status'=>1));
            $this->assign('nlist',$this->getChilds($rules,$id));
            $this->display();
        }
    }

    /**
     *编辑
     */
    public function edit(){
        $this->auth = new Auth();
        if(IS_POST){
            $data = I('post.');

            empty($data['id']) && $this->returnData('请选择操作项！');
            empty($data['name']) && $this->returnData('规则名称不能为空！');
            if(abslength($data['name']) > 50){
                $this->returnData('规则名称不能超过50个字符！');
            }

            empty($data['title']) && $this->$this->returnData('显示名称不能为空！');
            if(abslength($data['title']) > 30){
                $this->returnData('显示名称不能超过30个字符！');
            }

            //判断规则是否存在
            $where = array();
            $where['name'] = array('eq',$data['name']);
            $where['id'] = array('neq',$data['id']);
            $where['pid'] = $data['pid'];
            if($this->getRulesField($where,'id')){
                $this->returnData('该规则名称已存在！');
            }
            unset($where);

            empty($data['pid']) &&  $data['pid'] = 0;
            //empty($data['status']) &&  $data['status'] = 1;
            empty($data['sort']) &&  $data['sort'] = 0;

            if($data['pid']>0){
                $detail = $this->auth->getRulesInfo($data['pid']);
                if(!$detail)$this->returnData('该规则不存在！');
                $data['path'] = trim($detail['path'].'-'.$data['id'],'-');
            }else{
                $data['path'] = $data['id'];
            }

            $data['tid'] = empty($detail['tid'])?0:$detail['tid'];

            $status = $this->auth->addRules($data);
            if($status){
                unset($detail);
                unset($data);
                $this->clearCache();
                $this->returnData('修改规则成功！',1);
            }else{
                $this->returnData('修改规则失败！');
            }
        }else{
            $id = I('get.id');
            $rules = $this->auth->getRoleAuthListStructure(array('status'=>1));

            $data = $this->auth->getRulesInfo($id);
            $this->assign('nlist',$this->getChilds($rules,$data['pid']));

            $this->assign('data',$data);
            $this->assign('id',$data['id']);
            $this->display('add');
        }
    }

    /*
     * 删除规则
     * */
    public function delRules(){
        if(IS_GET){
            $id = I('get.id');
            if(empty($id))$this->returnData('请选择操作项！');

            $this->auth = new Auth();
            $status = $this->auth->checkRulesChild($id);
            if($status)$this->returnData('请先删除子节点！',2);

            if($this->auth->delRules($id)){
                $this->clearCache();
                $this->returnData('删除成功！',1);
            }else{
                $this->returnData('删除失败！');
            }
        }else{
            $this->returnData('请求方式错误！');
        }
    }

    /*
     * 获得所有自己且加修饰符
     * */
    public function getChilds($list,$pid=""){
        $str = '';
        foreach($list as $value){
            if($pid && intval($pid) == intval($value['id'])){
                $select = 'selected="selected"';
            }
            $str .= '<option value="'.$value['id'].'" '.$select.'>'.$this->getHierarchySeparator($value['path']).'└'.$value['title'].'</option>';
            $select = '';
            if($value['child']){
                $str .= $this->getChilds($value['child'],$pid);
            }
        }
        return $str;
    }

    /*
     * 根据层级生成分隔符
     * */
    private function getHierarchySeparator($path){
        $str = '';
        $num = $this->getPathHierarchy($path);
        for($i=0;$i<$num;$i++){
            $str .= $this->separated;
        }
        return $str;
    }

    /*
     * 通过PATH获取当前第几级
     * */
    public function getPathHierarchy($path){
        $array = explode('-',$path);
        $num = count($array)-1;
        return $num<0?0:$num;
    }

    /**
     * 获取规则任意字段
     * @param $where
     * @param $field
     * @return mixed
     */
    private function getRulesField($where,$field){
        $result =  M('auth_rule')->where($where)->cache(5)->getField($field);
        return $result;
    }

    /**
     * 获取节点html
     * @param $id
     * @param $title
     * @return string
     */
    private function get_rules_html($id,$title){
        $str ='';
        $str .='<li>';
        $str .='<p><img id="img_218" src="'.C('TMPL_PARSE_STRING.__PUBLIC__').'/Admin/images/off.png">';
        $str .='<span class="title">'.$title.'</span>';
        $str .='<span class="fr">';
        $str .='<a class="add_rules" data-id="'.$id.'" href="javascript:void(0);">添加子规则</a>';
        $str .=' -<a class="edit_rules" data-id="'.$id.'" href="javascript:void(0);">修改</a>';
        $str .=' -<a class="del_sub_rules" data-id="'.$id.'" style="cursor: pointer">删除</a>';
        $str .='</span>';
        $str .='</p>';
        $str .='</li>';

        return $str;
    }

    /**
     * 清除缓存
     */
    private function clearCache(){
        S(C('DB_PREFIX').'_auth_list_'.C('MANAGE_id'),null);
        S(C('DB_PREFIX').'_sys_rule_list_cache_html',null);
    }
}